import { useLoginStore } from "../store/modules/login";
import { useUserStore } from "@/store/modules/user";
import errorCode from "../utils/http/errorCode";
import BasicConfig from "@/utils/config";
import {
  loginByWechat as apiLogin,
  refreshToken as apiRefreshToken,
  loginBySms as apiSmsLogin,
} from "../api/Interface/login";
import {
  useGetRefreshTokenStorage,
  useGetTokenStorage,
  useRemoveLocationStorage,
  useSetLocationStorage,
} from "./useStorage";
import { eventBus } from "../enums/eventBus";

/**
 * 获取微信登录code 后台换取openid用
 */
export const useWechatLogin = async () => {
  return await new Promise((resolve, reject) => {
    uni.login({
      success: (res) => {
        console.log("平台登录code", res);
        // return
        const Store = useLoginStore();
        // 设置登录code值
        Store.setLoginCode(res.code);
        resolve({
          code: errorCode.success,
          data: res.code,
          msg: "",
        });
      },
      fail: (err) => {
        BasicConfig.toast({
          msg: "login接口调用失败，将无法正常使用开放接口等服务",
        });
        reject({
          code: 404,
          data: null,
          msg: "login接口调用失败，将无法正常使用开放接口等服务",
        });
      },
    });
  });
};

/**
 * 接口登录
 */
export const useLogin = async (param = {}) => {
  return new Promise(async (resolve, reject) => {
    const Store = useLoginStore();
    console.log("useLogin", param);
    const params = Object.assign(param, {
      wechatCode: Store.loginCode,
    });
    console.log("useLogin params", params);
    // 发送登录请求
    await apiLogin(params)
      .then((res) => {
        if (res.code === errorCode.success) {
          _saveLogin(res);
          resolve(res);
        } else {
          // BasicConfig.toast(res.msg);
          // reject(res);
          resolve(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * 手机验证码登录
 */
export const useSmsLogin = async (param = {}) => {
  return new Promise(async (resolve, reject) => {
    const Store = useLoginStore();
    console.log("useSmsLogin", param);
    const params = Object.assign(param, {
      wechatCode: Store.loginCode,
    });
    console.log("useSmsLogin params", params);
    // 发送登录请求
    await apiSmsLogin(params)
      .then((res) => {
        if (res.code === errorCode.success) {
          _saveLogin(res);
          resolve(res);
        } else {
          // BasicConfig.toast(res.msg);
          // reject(res);
          resolve(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * 刷新token
 */
export const useRefreshToken = (param = {}) => {
  return new Promise(async (resolve, reject) => {
    // 发送登录请求
    await apiRefreshToken(param, {
      custom: { auth: false, loading: false },
      header: {
        // Authorization: useGetRefreshTokenStorage(),
        // access_token: useGetRefreshTokenStorage(),
        Authorization: useGetTokenStorage(),
      },
    })
      .then((res) => {
        if (res.code === errorCode.success) {
          _saveToken(res);
          resolve(res);
        } else {
          // BasicConfig.toast(res.msg);
          // reject(res);
          resolve(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 退出
export const useLogout = () => {
  const LoginStore = useLoginStore();
  const UserStore = useUserStore();
  LoginStore.setLoginCode("");
  UserStore.setToken("");
  UserStore.setUserInfo({});
  useRemoveLocationStorage();
  uni.reLaunch({
    url: "/pages/index/index",
  });
};

/**
 * 弹出登录窗口
 */
export const useOpenLogin = (show = true) => {
  uni.$emit(eventBus.login.popup, show);
};

export const _saveLogin = (res) => {
  const Store = useUserStore();
  Store.setToken(
    `${res.data.token_type} ${res.data.access_token}`,
    `${res.data.token_type} ${res.data.refresh_token}`
  );
  // Store.setUserInfo(res.data);
};

export const _saveToken = (res) => {
  const Store = useUserStore();
  Store.setToken(
    `${res.data.token_type} ${res.data.access_token}`,
    `${res.data.token_type} ${res.data.refresh_token}`
  );
};
